<?php
namespace TicTacToe\Controller;
use \Core\MVC\ModelMap;
use \TicTacToe\Model\Board;

class IndexController {
	
	private $boardDao;
	
	public function index() {
		// get board
		$board = $this->boardDao->loadBoard();
		
		// do move
		if(isset($_GET["reset"])) {
			$board->clear();
		} elseif($board->getGameResult() == Board::RESULT_INPROGRESS) {
			for($i = 0; $i < 9; ++$i) {
				if (isset($_GET[$i])) {
					$board->placeSign($i, $board->whoseTurn());
					break;
				}
			}
		}
		
		// save board after move
		$this->boardDao->saveBoard($board);
		
		// check result
		$result = $board->getGameResult();
		
		return new ModelMap($result == $board::RESULT_INPROGRESS ? "TicTacToe/inprogress" : "TicTacToe/endgame", array(
			"board" => $board,
			"result" => $result,
		));
	}
	
	public function setBoardDao($boardDao) {
		$this->boardDao = $boardDao;
	}
}